﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using Website.Logger;
using DAL;
using UtilityExtensions;
using BOL.Ventas;
using BOL.UI;
using BOL.Cliente;
using BOL;
using BOL.Comun;
using WebLib;
using System.Web.Script.Services;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;

namespace UILGestion.VentaAdmin.OrdenVenta
{
    public partial class CuotaItemGrid : System.Web.UI.UserControl
    {
              
       
        protected void Page_Load(object sender, EventArgs e)
        {
           

            try
            {
                if (!this.IsPostBack)
                {
                    internalID.Value = (string)Request.QueryString["id"];
                    FormatForm();
                }
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

               
        }
        private void FormatForm()
        {
            var Lista= new ListValueBL();

            UIDDL.DataTextField = "descripcion";
            UIDDL.DataValueField = "idInternal";
            UIDDL.DataSource = Lista.GetOrdenVentaItem(internalID.Value.ToInt());
            UIDDL.DataBind();


            monedaDDL.DataTextField = "descripcion";
            monedaDDL.DataValueField = "idInternal";
            monedaDDL.DataSource = Lista.GetMoneda();
            monedaDDL.DataBind();


            idColeccionOrigen.Value = Parametros.GenerarID().ToString();
            idColeccionDestino.Value = Parametros.GenerarID().ToString();
            
            //BindDataItemDestion();
            //setFooterRow();
            
        }

        protected void CancelItem(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                itemGridView.EditIndex = -1;
                itemGridView.FooterRow.Visible = true;
                BindDataItemDestion();
                setFooterRow();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void AddItem(object sender, EventArgs e)
        {

            try
            {

                var origenLista = (List<OrdenVentaFormatoItemInfo>)Session[idColeccionOrigen.Value];
                var destinoLista = (List<OrdenVentaFormatoItemInfo>)Session[idColeccionDestino.Value];

                // solo el primero
                OrdenVentaFormatoItemInfo ordenVentaFormato = origenLista.First();

                DropDownList conceptoDDL =
                       ((DropDownList)itemGridView.FooterRow.FindControl("conceptoDDL"));

                TextBox fechaVencimientoEditTXT =
                    ((TextBox)itemGridView.FooterRow.FindControl("fechaVencimientoEditTXT"));

                TextBox totalTextBox =
                       ((TextBox)itemGridView.FooterRow.FindControl("totalTextBox"));

                //----------------------------
                // los montos no debe ser mayores
                var total=destinoLista.Sum(p=>p.total)+totalTextBox.Text.ToDecimal().Value;
                var totalorigen=origenLista.Sum(p => p.total);
                if (totalorigen < total)
                {
                    var disponible=totalorigen-destinoLista.Sum(p=>p.total);
                    throw new Exception("No debe pasar del monto {0:N} solo dispone de  {1:N} ".Fmt(totalorigen, disponible));
                }
                //----------------------------
                
                
                OrdenVentaFormatoItemInfo item = new OrdenVentaFormatoItemInfo("000000",
                                                conceptoDDL.SelectedValue.ToInt(),
                                                conceptoDDL.SelectedItem.Text,
                                                totalTextBox.Text.ToDecimal().Value,
                                                fechaVencimientoEditTXT.Text.ToDate().Value,
                                                totalTextBox.Text);

                List<OrdenVentaFormatoItemInfo> ds = (List<OrdenVentaFormatoItemInfo>)Session[idColeccionDestino.Value];




                ds.Add(item);

                Session[idColeccionDestino.Value] = ds;
                BindDataItemDestion();
                setFooterRow();
                SetEstadistica();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }



       
        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);
                              
                int idinternal = int.Parse(gv.DataKeys[e.RowIndex].Values[0].ToString());

                TextBox totalTextBox =
                    ((TextBox)gv.Rows[e.RowIndex].FindControl("totalTextBox"));
                string fechaVencimientoEditTXT =
                    ((TextBox)gv.Rows[e.RowIndex].FindControl("fechaVencimientoEditTXT")).Text;

                var origenLista = (List<OrdenVentaFormatoItemInfo>)Session[idColeccionOrigen.Value];
                var ds = (List<OrdenVentaFormatoItemInfo>)Session[idColeccionDestino.Value];
                
                var q = ds.Single(p => p.idInternal == idinternal);

                //----------------------------
                // los montos no deben ser mayores
                var total = origenLista.Where(p => p.idInternal != idinternal).Sum(p => p.total) + totalTextBox.Text.ToDecimal().Value;
                var totalorigen = origenLista.Where(p => p.idInternal != idinternal).Sum(p => p.total);
                if (  Math.Round(totalorigen) < Math.Round(total))
                {
                    var disponible = totalorigen - ds.Sum(p => p.total);
                    throw new Exception("No debe pasar del monto {0:N} solo dispone de  {1:N} ".Fmt(totalorigen, disponible));
                }
                //----------------------------

                q.Update(fechaVencimientoEditTXT.ToDate().Value, totalTextBox.Text.ToDecimal().Value);

                Session[idColeccionDestino.Value] = ds;

                gv.EditIndex = -1;

                BindDataItemDestion();
                setFooterRow();
                
                SetEstadistica();

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            try
            {
                itemGridView.EditIndex = e.NewEditIndex;
                BindDataItemDestion();
                itemGridView.FooterRow.Visible = false;
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        public void LoadSetCuota()
        {

            fechaLBL.Text = DateTime.Now.ToShortDateString();
           // usuarioLBL.Text = (string)Session["login.Empleado.descripcion"];
            //var ordenVetaItem = DbUtil.Db.OrdenVentaItems.Single(p => p.idInternal == UIDDL.SelectedValue.ToInt());
            LoadSaldoOrigen(UIDDL.SelectedValue.ToInt());
            Session[idColeccionDestino.Value]=new List<OrdenVentaFormatoItemInfo>();
            BindDataItemDestion();
            setFooterRow();
            SetEstadistica();

        }
        public void LoadSaldoOrigen(int  idordenVentaItem)
        {
            //traemos los saldos pendienste  por ser financiados

            var ordenVentaItem = DbUtil.Db.OrdenVentaItems.Single(p => p.idInternal == idordenVentaItem);
            monedaDDL.SelectedValue = ordenVentaItem.idMoneda.ToString();
            idTipoUITXT.Text = ordenVentaItem.UI.idTipoUI.ToString();
            tipoUITXT.Text = ordenVentaItem.UI.UITipo.descripcion;


            var q = from a in ordenVentaItem.OrdenVentaFormatos
                    where  a.total - a.totalPago-a.totalFin > 0
                            & a.idConcepto!=2  //bono
                            & a.idConcepto!=3 //CH
                            & a.idConcepto!=4
                    select new OrdenVentaFormatoItemInfo
                    {
                        concepto = a.ConceptoItem.descripcion,
                        idConcepto = a.idConcepto,
                        idInternal = a.idInternal,
                        numDocumento = a.numDocumento,
                        total = a.total - a.totalPago-a.totalFin,
                        fechaVencimientoStr=a.fechaVencimiento.ToShortDateString(),
                        totalStr = string.Format("{0} {1:N}", a.Moneda.simbol, a.total - a.totalPago)
                    };

             Session[idColeccionOrigen.Value] = q.ToList();
             BindDataItemOrgien();
            

        }

        //public void LoadSaldodestino(int idColeccion, int idParent)
        //{

        //    this.idColeccion.Value = idColeccion.ToString();
        //    this.internalID.Value = idParent.ToString();
        //    BindDataItem();


        //}

        private void SetEstadistica()
        {
             List<OrdenVentaFormatoItemInfo> dsOrigen = (List<OrdenVentaFormatoItemInfo>)Session[idColeccionOrigen.Value];
             List<OrdenVentaFormatoItemInfo> dsDestino = (List<OrdenVentaFormatoItemInfo>)Session[idColeccionDestino.Value];

            totalSaldoLBL.Text=dsOrigen.Sum(p=>p.total).ToString("N");
            totalCuotaLBL.Text = dsDestino.Sum(p => p.total).ToString("N");
            estadisticaUPNL.Update();
        }
        
        protected void DeleteItem(object sender, EventArgs e)
        {
            try
            {

                ImageButton lnkRemove = (ImageButton)sender;
                int idInternal = int.Parse(lnkRemove.CommandArgument.ToString());

                var ds = (List<OrdenVentaFormatoItemInfo>)Session[idColeccionDestino.Value];

                var drw = (from a in ds
                           where a.idInternal== idInternal
                           select a).First();


                ds.Remove(drw);
                
                //eRolList.Tables[1].Rows.Remove(drw);

                Session[idColeccionDestino.Value.ToString()] = ds;

                BindDataItemDestion();
                this.SetEstadistica();
                setFooterRow();

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void DeleteOrigenItem(object sender, EventArgs e)
        {
            try
            {

                ImageButton lnkRemove = (ImageButton)sender;
                int idInternal = int.Parse(lnkRemove.CommandArgument.ToString());

                var  ds = (List<OrdenVentaFormatoItemInfo>)Session[idColeccionOrigen.Value];

                var drw = (from a in ds
                           where a.idInternal== idInternal
                           select a).First();


                ds.Remove(drw);
                
                

                Session[idColeccionOrigen.Value.ToString()] = ds;

                BindDataItemOrgien();
                SetEstadistica();




            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        
        private void resetEmpty()
        {
            if (itemGridView.Rows.Count == 0)
            {
                List<OrdenVentaFormatoItemInfo> itemList0 = new List<OrdenVentaFormatoItemInfo>();
                OrdenVentaFormatoItemInfo itemcero = new OrdenVentaFormatoItemInfo();

                itemList0.Add(itemcero);
                itemGridView.DataSource = itemList0;
                itemGridView.DataBind();
                itemGridView.Rows[0].Visible = false;
            }

        }

        private void resetEmptyOrigen()
        {
            if (origenGridView.Rows.Count == 0)
            {
                List<OrdenVentaFormatoItemInfo> itemList0 = new List<OrdenVentaFormatoItemInfo>();
                OrdenVentaFormatoItemInfo itemcero = new OrdenVentaFormatoItemInfo();

                itemList0.Add(itemcero);
                origenGridView.DataSource = itemList0;
                origenGridView.DataBind();
                origenGridView.Rows[0].Visible = false;
            }

        }

        public void BindDataItemOrgien()
        {

            List<OrdenVentaFormatoItemInfo> ds = (List<OrdenVentaFormatoItemInfo>)Session[idColeccionOrigen.Value];

            origenGridView.DataSource = ds;
            origenGridView.DataBind();
            resetEmptyOrigen();
            orgienUPNL.Update();

        }

        public void BindDataItemDestion()
        {

            List<OrdenVentaFormatoItemInfo> ds = (List<OrdenVentaFormatoItemInfo>)Session[idColeccionDestino.Value];
            var totalOrgien = ((List<OrdenVentaFormatoItemInfo>)Session[idColeccionOrigen.Value]).Sum(p=>p.total);
            var totalDestino = ds.Sum(p=>p.total);
            // si ya llego al fina no mostrar la grilla de add
            itemGridView.ShowFooter = true;
            if (totalOrgien == totalDestino)
            {
                itemGridView.ShowFooter = false;
            }


            itemGridView.DataSource = ds;
            itemGridView.DataBind();
            resetEmpty();
            nuevaCuotaFinUPNL.Update();

        }

        protected void UIDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int id=UIDDL.SelectedValue.ToInt();
                if (id > 0)
                {

                    LoadSaldoOrigen(id);
                    cabUPNL.Update();//no actualuza en cadena
                    SetEstadistica();
                }
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }

        private void setFooterRow()
        {

            DropDownList conceptoDDL = ((DropDownList)itemGridView.FooterRow.FindControl("conceptoDDL"));
            
            var listaOrigen = ((List<OrdenVentaFormatoItemInfo>)Session[idColeccionDestino.Value]).Select(p=>p.idConcepto);
           //quitamos los ya utilizados en la venta 

            var listayaUso = from a in DbUtil.Db.OrdenVentaFormatos
                    where a.idOrdenVentaItem == idOrdenVentaitem
                    select a.idConcepto;
            

                                                                  //--------------
            var concepto = from a in DbUtil.Db.ConceptoItems
                           where !listaOrigen.Contains(a.idInternal)
                           & !listayaUso.Contains(a.idInternal)
                                   & a.idConcepto == 2
                           select a;
            
            conceptoDDL.DataValueField = "idInternal";
            conceptoDDL.DataTextField = "descripcion";
            conceptoDDL.DataSource = concepto;
            conceptoDDL.DataBind();



        }

        public List<OrdenVentaFormatoItemInfo> ItemOrgien {

            get
            {
                var lista=(List<OrdenVentaFormatoItemInfo>)Session[idColeccionOrigen.Value];
                return lista;
            }
            
            
        
        }

        public List<OrdenVentaFormatoItemInfo> ItemDestino {
            get
            {
                var lista = (List<OrdenVentaFormatoItemInfo>)Session[idColeccionDestino.Value];
                return lista;
            }
        
        }
        public string comentario
        {

            get
            {
                
                return comentarioTXT.Text;
            }



        }
        public int idOrdenVentaitem
        {

            get
            {

                return UIDDL.Text.ToInt();
            }



        }

       
        public int idMoneda
        {

            get
            {

                return monedaDDL.SelectedValue.ToInt();
            }



        }
        public int idTipoUI
        {

            get
            {

                return idTipoUITXT.Text.ToInt();
            }



        }
    }
}